#ifndef SERIALPORTSYNC_H
#define SERIALPORTSYNC_H

#include <QObject>
#include <QtSerialPort/QSerialPort>
#include <QTimer>

class SerialPortSync : public QObject
{
    Q_OBJECT
public:
    explicit SerialPortSync(QObject *parent = nullptr);
    ~SerialPortSync();

    // 打开串口
    bool open(const QString &portName,
             qint32 baudRate = QSerialPort::Baud9600,
             QSerialPort::DataBits dataBits = QSerialPort::Data8,
             QSerialPort::Parity parity = QSerialPort::NoParity,
             QSerialPort::StopBits stopBits = QSerialPort::OneStop,
             QSerialPort::FlowControl flowControl = QSerialPort::NoFlowControl);
    
    // 关闭串口
    void close();
    
    // 同步发送并等待接收数据
    // 返回接收到的数据，如果超时则返回空
    QByteArray sendSync(const QByteArray &data, int timeout = 3000);

    // 检查串口是否打开
    bool isOpen() const;

signals:
    void responseReceived();
    void timeoutOccurred();


private slots:
    void onReadyRead();
    void onTimeout();

private:
    QSerialPort *m_serial;
    QByteArray m_receiveBuffer;
    QTimer *m_timer;
    bool m_waitingForResponse;
};

#endif // SERIALPORTSYNC_H
